package org.kernely.stream;

import java.util.HashSet;

import org.kernely.security.dao.PermissionDAO;
import org.kernely.security.ui.SecurityUIBundle;
import org.kernely.security.dao.UserDetailsDAO;
import org.kernely.security.persistence.User;
import org.kernely.security.persistence.UserDetails;
import org.kernely.stream.dao.StreamDAO;
import org.kernely.stream.persistence.Stream;
import org.osgi.service.event.Event;
import org.osgi.service.event.EventHandler;

/**
 * Manage events for the stream bundle.
 */
public class StreamEventsHandler implements EventHandler {

	/**
	 * Constructor of the event handler
	 */
	public StreamEventsHandler() {
	}

	@Override
	/**
	 * Handle events managed by the event admin
	 */
	public void handleEvent(Event event) {
		String title = (String) event.getProperty("title");

		// When a new user has been created, creates automatically a stream
		if (title.equals(SecurityUIBundle.NEW_USER)){
			UserDetailsDAO uddao = UserDetailsDAO.getInstance();
			StreamDAO sdao = StreamDAO.getInstance();

			User user = (User) event.getProperty("user");
			UserDetails userDetails = uddao.getUserDetails(user);
			Stream userStream = new Stream();
			String streamUid = userDetails.getUser().getLogin(); 
			String streamCategory = Stream.CATEGORY_USERS;
			HashSet<User> usersSet = new HashSet<User>();
			usersSet.add(userDetails.getUser());
			
			// An user automatically subscribes to his stream, and can write on it and delete his own messages
			userStream.setUid(streamUid);
			userStream.setCategory(Stream.CATEGORY_USERS);
			userStream.setRedactors(usersSet);
			userStream.setSubscriptors(usersSet);

			// An user has the permission to write and subscribe to his own streamstreams			
			StreamBundle.getSecurityService().grantAuthorization(user, streamCategory+":write,subscribe,deletemessages:"+streamUid);
			userStream.setTitle(userDetails.getFirstname()+" "+userDetails.getName()+"'s stream");
			sdao.saveStream(userStream);
			
			// An user can subscribe to the streams of all users
			StreamBundle.getSecurityService().grantAuthorization(user, Stream.CATEGORY_USERS+":subscribe:*");
		}
		else
			// When a user has been updated, modify the stream state to locked/unlocked if the user is disabled/enabled.
			if (title.equals(SecurityUIBundle.EDIT_USER)){
				StreamDAO sdao = StreamDAO.getInstance();
				User user = (User) event.getProperty("user");
				// Get the user's stream
				Stream stream = sdao.findStream(Stream.CATEGORY_USERS, user.getLogin());

				// Modify the state of the stream if needeed.
				if (user.getEnabled() == 0 && stream.getLocked() == 0){
					// User disabled, stream not locked, the stream must be locked
					stream.setLocked(1);
					sdao.updateStream(stream);
				}
				else if (user.getEnabled() == 1 && stream.getLocked() == 1){
					// User enabled, stream not locked, the stream must be locked
					stream.setLocked(0);
					sdao.updateStream(stream);
				}
			}
	}
}